package net.mhelvens.deltaprofiles;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PatternMatcher;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

public class RuleEditActivity extends FragmentActivity {
	@SuppressWarnings("unused") private static final String TAG = RuleEditActivity.class.getSimpleName();

	static public final String NEW_RULE    = "net.mhelvens.deltaprofiles.action.NEW_RULE";
	static public final String EDIT_RULE   = "net.mhelvens.deltaprofiles.action.EDIT_RULE";
	
	static public final int RESULT_DELETED = RESULT_FIRST_USER + 0;
	
	private Rule mRule;
	
	private FragmentPagerAdapter mSectionsPagerAdapter;
	private ActionBar            mActionBar;
	private ViewPager            mViewPager;
	
	protected void prepareDatabase() {
		if (getIntent().getAction().equals(NEW_RULE)) {
			mRule = Rule.getNew();
		} else if (getIntent().getAction().equals(EDIT_RULE)) {
			assert getIntent().hasExtra("id");
			mRule = Rule.get(getIntent().getLongExtra("id", -1));
		}
	}
	
	protected void collectViews() {
		mSectionsPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
			public int getCount() { return 3; }
			
			public Fragment getItem(int position) {
				switch (position) {
				case 0: return new RuleEditGeneralFragment  (mRule);
				case 1: return new RuleEditConditionFragment(mRule);
				case 2: return new RuleEditEffectsFragment  (mRule);
				} return null;
			}
			
			public CharSequence getPageTitle(int position) {
				switch (position) {
				case 0: return getString(R.string.general  );
				case 1: return getString(R.string.condition);
				case 2: return getString(R.string.effects  );
				} return null;
			}
		};
		
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mActionBar = getActionBar();
	}
	
	protected void setupViews() {
		// Prepare the action bar
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		mActionBar.setDisplayHomeAsUpEnabled(true);
		mActionBar.setDisplayShowTitleEnabled(true);
		
		// Setting up the tabs and slider
		mViewPager.setAdapter(mSectionsPagerAdapter);
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			mActionBar.addTab(mActionBar.newTab()
			          .setText(mSectionsPagerAdapter.getPageTitle(i))
			          .setTabListener(new ActionBar.TabListener() {
			        		// Tab Click --> Pager View Select
			        		//
			        		public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
			        			mViewPager.setCurrentItem(tab.getPosition());
			        		}

			        		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			        		} // intentionally empty

			        		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			        		} // intentionally empty
			          }));
		}
		
		// Swipe --> Tab Select
		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			public void onPageSelected(int position) {
				mActionBar.setSelectedNavigationItem(position);
			}
		});
		
		// Rule name change --> Activity title change
		IntentFilter filter = new IntentFilter(Rule.ACTION_BROADCAST_MODIFY);
    	filter.addDataPath(mRule.uri_name().getPath(), PatternMatcher.PATTERN_PREFIX);
		LocalBroadcastManager.getInstance(this.getApplicationContext()).registerReceiver(
                new BroadcastReceiver() {
					public void onReceive(Context context, Intent intent) {
						setTitle(mRule.name());
					}
                }, filter);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rule_edit);
		
		prepareDatabase();
		collectViews();
		setupViews();
		
		setResult(RESULT_OK, getIntent());
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_rule_edit, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.delete: delete();
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void finishFromDeletedRule() {
		setResult(RESULT_DELETED);
		finish();
	}
	
	@Override
	protected void onRestart() {
		if (mRule.isDeleted())
			finishFromDeletedRule();
		super.onResume();
	}
	
	protected void delete() {
		mRule.delete();
		finishFromDeletedRule();
	}
	
}
